import React, { CSSProperties, HTMLAttributes, useMemo, useState } from 'react';
import classNames from 'classnames';
import './index.less';
import RowContext from './RowContext';

interface RowProps extends HTMLAttributes<HTMLDivElement> {
  align?: 'top' | 'middle' | 'bottom';
  justify?: 'start' | 'end' | 'center' | 'space-around' | 'space-between';
  wrap?: boolean;
  gutter?: number;
}
export type Breakpoint = 'xxl' | 'xl' | 'lg' | 'md' | 'sm' | 'xs';
export type ScreenMap = Partial<Record<Breakpoint, true>>;

export default function Row(props: RowProps) {
  const { align, justify, wrap, gutter, className, children, style } = props;

  const getGutter = () => {
    const results = [0, 0];
    const normalizedGutter = Array.isArray(gutter) ? gutter : [gutter, 0];
    normalizedGutter.forEach((g, index) => {
      results[index] = g || 0;
    });

    return results;
  };
  const rowStyle: CSSProperties = {};
  const gutters = getGutter();

  const horizontalGutter = gutters[0] > 0 ? gutters[0] / -2 : undefined;
  const verticalGutter = gutters[1] > 0 ? gutters[1] / -2 : undefined;

  if (horizontalGutter) {
    rowStyle.marginLeft = horizontalGutter;
    rowStyle.marginRight = horizontalGutter;
  }

  if (verticalGutter) {
    rowStyle.marginTop = verticalGutter;
    rowStyle.marginBottom = verticalGutter;
  }

  [, rowStyle.rowGap] = gutters;
  const [gutterH, gutterV] = gutters;

  const cn = classNames(className, 'ant-row', {
    'ant-row-no-wrap': wrap,
    [`ant-row-justify-${justify}`]: justify,
    [`ant-row-align-${align}`]: align,
  });

  const rowContext = useMemo(
    () => ({ gutter: [gutterH, gutterV] as [number, number], wrap }),
    [gutterH, gutterV, wrap],
  );

  return (
    <RowContext.Provider value={rowContext}>
      <div style={{ ...rowStyle, ...style }} className={cn}>
        {children}
      </div>
    </RowContext.Provider>
  );
}
